package com.ruoyi.business.sundry.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.business.base.PageParam;
import com.ruoyi.business.sundry.domain.vo.JbRawMaterialPriceHistoryVo;
import com.ruoyi.business.sundry.service.JbRawMaterialPriceHistoryService;
import org.springframework.stereotype.Service;
import com.ruoyi.business.base.JoBaseServiceImpl;
import com.ruoyi.business.sundry.mapper.JbRawMaterialPriceHistoryMapper;
import com.ruoyi.business.sundry.domain.JbRawMaterialPriceHistory;

import java.util.List;
import java.util.StringJoiner;

/**
 * 原材料价格历史Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-11
 */
@Service
public class JbRawMaterialPriceHistoryServiceImpl
        extends JoBaseServiceImpl<JbRawMaterialPriceHistoryMapper, JbRawMaterialPriceHistory>
        implements JbRawMaterialPriceHistoryService
{

    @Override
    public List<JbRawMaterialPriceHistoryVo> listData(PageParam page, JbRawMaterialPriceHistory jbRawMaterialPriceHistory)
    {
        StringJoiner sql = new StringJoiner(" ").add("""
                SELECT
                	rmph.material_name,
                	rmph.material_price_id,
                	rmph.material_id,
                	t.yearMonth,
                	rmph.latest_price\s
                FROM
                	jb_raw_material_price_history rmph
                	INNER JOIN (
                	SELECT
                		DATE_FORMAT( create_time, '%Y-%m' ) AS yearMonth,
                		MAX( id ) AS maxId\s
                	FROM
                		jb_raw_material_price_history\s
                	WHERE
                		del_flag = 0\s
                """);
        sql.add(joSqlUtil.sqlIf(String.format(" and create_time>='%s'",page.getStartTime()), page.getStartTime()));
        sql.add(joSqlUtil.sqlIf(String.format(" and create_time<='%s'",page.getEndTime()), page.getEndTime()));
        sql.add(joSqlUtil.sqlIf(String.format(" and material_price_id='%s'",jbRawMaterialPriceHistory.getMaterialPriceId()),
                jbRawMaterialPriceHistory.getMaterialPriceId()));
        sql.add("""
                GROUP BY
                		yearMonth\s
                	ORDER BY
                	yearMonth\s
                	) t ON rmph.id = t.maxId
                """);
        return joSqlUtil.jsonToEntity(baseMapper.findJson(sql.toString()),JbRawMaterialPriceHistoryVo.class);
    }
}
